const db = wx.cloud.database();
const forecast_table = db.collection('forecast_table');
const user_table=db.collection('user_table');
const forecastJoin_table=db.collection('forecastJoin_table');

const _ = db.command;
//用全局变量
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
maxlength:0,
//遮罩层开关    
show: false,
//是否预测过
join:0,

userList:{},
forecastId:'',
forecast:{
},
forecastInfo:{},
//比例对象数组 分别有 预测结果 预测人数 预测比例 预测条颜色
percentage:[],
color:['rgb(233, 230, 84)','rgba(209, 82, 23, 0.856)','cornflowerblue','green','orange',],

  },

 
//选择预测结果之后弹出投入积分框
select(e){
 
  this.setData({
    show: true,
    forecastInfo:{
      forecastResult:e.currentTarget.dataset.result,
      inputNumber:0,
    }
  })
  console.log(this.data.forecastInfo)
},
getInputValue(e){
console.log(e)
this.setData({
  ['forecastInfo.inputNumber']: e.detail.value

})
console.log(this.data.forecastInfo.inputNumber)
},

sub(e) {//提交工作内容
//   /^\d+$/.test(val)  正则表达式判断string类型中是否有非数字 无则return true
if(/^\d+$/.test(this.data.forecastInfo.inputNumber)) {
  this.setData({
    ['forecastInfo.inputNumber']: parseInt(this.data.forecastInfo.inputNumber) 
  
  })
console.log(this.data.forecastInfo.inputNumber)
  if(this.data.forecastInfo.inputNumber>this.data.userList.userNumber){
    wx.showToast({
      title: '您的积分不足！',
      duration: 1000,
      icon:'error',
    })

  }else if(this.data.forecastInfo.inputNumber==0){
    wx.showToast({
      title: '积分不能为空！',
      duration: 1000,
      icon:'error',
    })
  }
 
 else{
  wx.showModal({
    title: '提示',
    content: '确定投入预测？',
    success :res=> {
      if (res.confirm) {
        console.log('用户点击确定')
       
        forecastJoin_table.add({
          data:{
          forecastId: this.data.forecastId,
          forecastResult:this.data.forecastInfo.forecastResult,
          inputNumber:this.data.forecastInfo.inputNumber,
          result:'',
          userId:app.globalData.openid,
          getNumber:0,//活动结束后获得的积分
          
        
          
          },
          success:res=>{
        console.log('添加成功')
      
          }
            
      })

      user_table.where({
        userId:app.globalData.openid
      }).update({
        data: {
          userNumber:this.data.userList.userNumber-this.data.forecastInfo.inputNumber,
          joinNumber:_.inc(1),
       
        },
        success: res => {
        console.log('用户信息更新成功')
        },
        fail: err => {
       
          console.error('[数据库] [更新记录] 失败：', err)
        }
      })

      forecast_table.where({
        forecastId:this.data.forecastId
      }).update({
        data: {
          people:_.inc(1),
          reward:_.inc(this.data.forecastInfo.inputNumber),
       
        },
        success: res => {
        console.log('该预测信息更新成功')
        },
        fail: err => {
       
          console.error('[数据库] [更新记录] 失败：', err)
        }
      })
      
      wx.reLaunch({
        url: '../index/index',
      })
      


      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
 
 
  this.setData({
    show: false
  })

 }

} 

else{
  wx.showToast({
    title: '积分非法！',
    duration: 1000,
    icon:'error',
  })

}


   
 

 
},
//关闭投入积分框
 close(e){
  this.setData({
    show: false
  })

 },

 //分享给好友
 onShareAppMessage:function(res) {
   var id=this.data.forecastId
   var title=this.data.forecast.title
   console.log(id)
  if (res.from == 'button') {
      console.log(res.target, res)
  }

  return {
    title:'快来参与竞猜吧！',
    path:"/pages/index/index?id="+id,//这里是被分享的人点击进来之后的页面
    imageUrl: '../../assets/img1/share.jpg'//这里是图片的路径
  }
},


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
console.log(options)
this.setData({
  forecastId:options.id
})
console.log(this.data.forecastId)
//判断是否参加过
this.ifJoin()

this.getForecast()
.then(this.getForecastJoin)

//获取用户信息
this.getUser()


  },
//获取forecast表中的信息
  getForecast(e){
    console.log('先拿forecast表数据 1')
    var p=  new Promise((resolve,reject)=>{
   //先拿forecast表数据 1
forecast_table.where({
 
  forecastId:this.data.forecastId
}).get({
  success:(res)=>{
    console.log(res.data)

    this.setData({
      forecast:res.data[0],  
    })
    console.log(this.data.forecast)
    console.log('先拿forecast表数据 完成')
   resolve()
  },
  fail(err) {
 console.log('取数据失败')
 resolve()
  }
      
  })
  
     
      })
      return p

  },
  //获取参与表中的信息
  getForecastJoin(e){
    console.log('第二步开始')
    let PromiseArr = []
    for (let i=0;i<this.data.forecast.result.length;i++){
   
   PromiseArr.push(new Promise((resolve, reject) => {
      forecastJoin_table.where({
   
        forecastId:this.data.forecastId,
        forecastResult:this.data.forecast.result[i]
    
      }).count({
        success:(res)=>{
          console.log(res.total)
    this.data.percentage.push({
      result:this.data.forecast.result[i],
      people:res.total,
      width:0,
      color:'',
    })
  
   
    console.log( this.data.percentage)
   
    resolve()
         
        }
            
        })
      }))

   }
  
   Promise.all(PromiseArr).then(res => {
    console.log('全部完成')
    this.showPercentage()

  })

    },
//显示占比
  showPercentage(e){
    var p=  new Promise((resolve,reject)=>{
      console.log('最后值都取到了 才显示比例条 3')
  //最后值都取到了 才显示比例条 3
var percentage=this.data.percentage
for(let i=0;i<this.data.forecast.result.length;i++){

 let a= (parseFloat( (this.data.percentage[i].people/this.data.forecast.people).toFixed(3))*100).toFixed(2) 

  this.setData({
    ['percentage['+i+'].width']:a,
    ['percentage['+i+'].color']:this.data.color[i],
    ['percentage['+i+'].result']:percentage[i].result,
    ['percentage['+i+'].people']:percentage[i].people,
    success :(res)=> {
      resolve() 
    }

  })
}
console.log(this.data.percentage)
console.log('最后值都取到了 才显示比例条 完成')
    })
    return p


  },
  //获取用户的信息
  getUser(e){
    user_table.where({
      //审核状态为1 且按时间顺序取出
      userId:app.globalData.openid
    }).get({
      success:(res)=>{
        console.log(res.data)
       let maxlength=res.data[0].userNumber.toString().length

        this.setData({
          userList:res.data[0],  
          maxlength:maxlength
        })
        
        console.log(this.data.userList)
        console.log(this.data.maxlength)
      },
      fail(err) {
        console.log(err)
    
      }
          
      })


  },

//判断是否以及参与过预测 从而个性化设置
  ifJoin(e){
   forecastJoin_table.where({
      userId:app.globalData.openid,
      forecastId:this.data.forecastId
    }).get({
      success:(res)=>{
        
       if(res.data.length==0){           
     
}else{
console.log(res.data)
        this.setData({
          ['forecastInfo.result']: res.data[0].forecastResult,  
          join:1,

        })
console.log(this.data.join)
console.log(this.data.forecastInfo.result)
       }

      },
      fail(err) {
       console.log(err)
    }    
      })


    },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

 

})

